const GoodsDB = require("../model/sqlite/goods");
const util = require("../common/util");

// 添加商品,测试通过
function addGoods(req, res) {
  (async () => {
    try {
      // const requiredFields = ['seller', 'goods_name', 'goods_desc', 'goods_price',
      //     'goods_stock', 'goods_detail'];
      // const missing = requiredFields.filter(field => !(field in req.body));
      // if (missing.length > 0) {
      //     return util.FormatJSONData(res, 400, '缺少必要参数', { missing });
      // }
      util.log("###############");
      const goods = {
        seller: req.body.seller,
        goods_name: req.body.goods_name,
        goods_desc: req.body.goods_desc,
        goods_price: parseFloat(req.body.goods_price),
        goods_stock: parseInt(req.body.goods_stock),
        goods_detail: parseInt(req.body.goods_detail),
        goods_create_time: new Date().toISOString(),
        goods_update_time: new Date().toISOString(),
      };

      const db = GoodsDB.getInstance();
      await db.connect();
      util.log(`商品${goods.goods_name}添加中`);
      const result = await db.add(goods);
      if (!result) {
        res.status(301).json(util.FormatJSONData(301, "请求失败"));
      }
      util.log(`商品${goods.goods_name}添加成功`);
      res
        .status(201)
        .json(util.FormatJSONData(201, "商品添加成功", { goods: result }));
    } catch (err) {
      util.err("添加商品失败", err);
      res.status(500).json(util.FormatJSONData(500, "服务器内部错误"));
    }
  })();
}

// 添加商品,测试通过
function addImg(req, res) {
  (async () => {
    try {
      const goods = {
        goods_id: parseInt(req.body.goods_id),
        img_url: req.body.url,
      };
      const db = GoodsDB.getInstance();
      await db.connect();

      const result = await db.addImg(goods);
      if (!result) {
        res.status(301).json(util.FormatJSONData(301, "请求失败"));
      }
      res
        .status(201)
        .json(util.FormatJSONData(201, "图片添加成功", { goods: result }));
    } catch (err) {
      util.err("添加图片失败", err);
      res.status(500).json(util.FormatJSONData(500, "服务器内部错误"));
    }
  })();
}

// function getAll(req,res){
//     (async () => {
//         try {
//             const limit = parseInt(req.query.limit) < 0 ? -1 : parseInt(req.query.limit);
//             const offset = parseInt(req.query.offset) < 0 ? -1 : parseInt(req.query.offset);
//             const db = GoodsDB.getInstance();
//             await db.connect();

//             const result = await db.findByName([], limit, offset);
//             if (!result.length) {
//                 res.json(util.FormatJSONData(403, '查询结果为空'));
//             } else {
//                 util.log(result);
//                 res.json(util.FormatJSONData(201, '查询商品成功', result));
//             }
//         } catch (err) {
//             console.log(err);
//             util.FormatJSONData(res, 500, '服务器内部错误');
//         }
//     })()
// }

// 通过商品查询商品，测试通过

// function getAll(req, res) {
//   (async () => {
//     try {
//       const limit =
//         parseInt(req.query.limit) < 0 ? -1 : parseInt(req.query.limit);
//       const offset =
//         parseInt(req.query.offset) < 0 ? -1 : parseInt(req.query.offset);
//       const db = GoodsDB.getInstance();
//       await db.connect();

//       const result = await db.findByName("", limit, offset); // 获取原始数据

//       // 转换图片格式
//       const formattedResult = result.map((item) => ({
//         ...item,
//         img_urls: item.img_urls ? item.img_urls.split(",") : [],
//       }));

//       if (!formattedResult.length) {
//         res.json(util.FormatJSONData(403, "查询结果为空"));
//       } else {
//         util.log(formattedResult);
//         res.json(util.FormatJSONData(201, "查询商品成功", formattedResult));
//       }
//     } catch (err) {
//       console.log(err);
//       util.FormatJSONData(res, 500, "服务器内部错误");
//     }
//   })();
// }

// function getAll(req, res) {
//   (async () => {
//     try {
//       // 参数处理
//       const limit = parseInt(req.query.limit) || 10;
//       const offset = parseInt(req.query.offset) || 0;
//       const db = GoodsDB.getInstance();
//       await db.connect();

//       // 并行查询数据和总数
//       const [data, total] = await Promise.all([
//         db.findByName("", limit, offset), // 查询数据
//         db.getTotalCount(), // 新增总数查询方法
//       ]);

//       // 处理图片格式
//       const formattedData = data.map((item) => ({
//         ...item,
//         img_urls: item.img_urls ? item.img_urls.split(",") : [],
//       }));

//       res.json(
//         util.FormatJSONData(200, "查询成功", {
//           total,
//           data: formattedData,
//           currentPage: Math.floor(offset / limit) + 1,
//           totalPages: Math.ceil(total / limit),
//         })
//       );
//     } catch (err) {
//       console.error(err);
//       util.FormatJSONData(res, 500, "服务器内部错误");
//     }
//   })();
// }

function getAll(req, res) {
  (async () => {
    try {
      const limit = parseInt(req.query.limit) || 10;
      const offset = parseInt(req.query.offset) || 0;
      const db = GoodsDB.getInstance();
      await db.connect();

      // 获取分页数据（现在返回的是包含total和data的对象）
      const { total, data } = await db.findByName("", limit, offset);

      // 转换图片格式
      const formattedData = data.map((item) => ({
        ...item,
        img_urls: item.img_urls ? item.img_urls.split(",") : [],
      }));

      res.json(
        util.FormatJSONData(200, "查询成功", {
          total,
          data: formattedData,
          currentPage: Math.floor(offset / limit) + 1,
          totalPages: Math.ceil(total / limit),
        })
      );
    } catch (err) {
      console.error(err);
      util.FormatJSONData(res, 500, "服务器内部错误");
    }
  })();
}

function getGoodsById(req, res) {
  (async () => {
    try {
      const goodsId = parseInt(req.params.goods_id);
      if (isNaN(goodsId)) {
        return res.json(util.FormatJSONData(400, "无效的商品ID"));
      }

      const db = GoodsDB.getInstance();
      await db.connect();

      const goods = await db.findById(goodsId); // 已扩展：返回商品 + first_img_url

      if (!goods) {
        return res.json(util.FormatJSONData(404, "商品不存在"));
      }

      // 可选：如果还需要返回多图列表，可从 imgs 表中获取所有图片（需另外封装）
      // 这里只返回第一张图，结构清晰简洁
      res.json(
        util.FormatJSONData(200, "查询商品成功", {
          ...goods,
          first_img_url: goods.first_img_url || null,
        })
      );

      util.log(`查询结果：${goods.goods_name}`);
    } catch (err) {
      console.error(err);
      res.json(util.FormatJSONData(500, "服务器内部错误"));
    }
  })();
}

// 通过商品名称查询商品，测试通过
// function getGoodsByName(req, res) {
//   (async () => {
//     try {
//       const goods_name = req.query.goods_name;
//       if (!goods_name) {
//         return res.json(util.FormatJSONData(400, "请输入商品名称"));
//       }
//       const limit =
//         parseInt(req.query.limit) < 0 ? -1 : parseInt(req.query.limit);
//       const offset =
//         parseInt(req.query.offset) < 0 ? -1 : parseInt(req.query.offset);
//       const db = GoodsDB.getInstance();
//       await db.connect();
//       const result = await db.findByName(goods_name, limit, offset);
      
//       if (!result.length) {
//         res.json(util.FormatJSONData(403, "查询结果为空"));
//       } else {
//         util.log(result);
//         res.json(util.FormatJSONData(201, "查询商品成功", result));
//       }
//     } catch (err) {
//       util.FormatJSONData(res, 500, "服务器内部错误");
//     }
//   })();
// }

function getGoodsByName(req, res) {
  (async () => {
    try {
      const limit = parseInt(req.query.limit) || 10;
      const offset = parseInt(req.query.offset) || 0;
      const goods_name = req.query.goods_name;
      const db = GoodsDB.getInstance();
      await db.connect();

      // 获取分页数据（现在返回的是包含total和data的对象）
      const { total, data } = await db.findByName(goods_name, limit, offset);

      // 转换图片格式
      const formattedData = data.map((item) => ({
        ...item,
        img_urls: item.img_urls ? item.img_urls.split(",") : [],
      }));

      res.json(
        util.FormatJSONData(200, "查询成功", {
          total,
          data: formattedData,
          currentPage: Math.floor(offset / limit) + 1,
          totalPages: Math.ceil(total / limit),
        })
      );
    } catch (err) {
      console.error(err);
      util.FormatJSONData(res, 500, "服务器内部错误");
    }
  })();
}

// 通过商品类别查询商品，测试通过
function getGoodsByCategory(req, res) {
  (async () => {
    try {
      const goods_category = req.query.goods_category;
      const limit =
        parseInt(req.query.limit) < 0 ? -1 : parseInt(req.query.limit);
      const offset =
        parseInt(req.query.offset) < 0 ? -1 : parseInt(req.query.offset);
      const db = GoodsDB.getInstance();
      await db.connect();
      const goods = await db.findByCategory(goods_category, limit, offset);
      if (goods.length == 0) {
        res.json(util.FormatJSONData(403, "查询结果为空", goods));
      } else {
        res.json(util.FormatJSONData(200, "查询商品成功", goods));
      }
    } catch (err) {
      util.FormatJSONData(res, 500, "服务器内部错误");
    }
  })();
}

function getGoodsBySeller(req, res) {
  (async () => {
    try {
      const seller = req.query.seller;
      const limit = parseInt(req.query.limit) || 10; // 默认10条
      const offset = parseInt(req.query.offset) || 0; // 默认从0开始
      const db = GoodsDB.getInstance();
      await db.connect();
      // 并行查询数据和总数
      const [goods, total] = await Promise.all([
        db.findBySeller(seller, limit, offset),
        db.findBySellerTotal(seller),
      ]);
      if (!goods.length) {
        return res.json(
          util.FormatJSONData(404, "查询结果为空", {
            total: 0,
            data: [],
          })
        );
      }
      console.log("#########");
      util.log(`查询结果：${goods.length}条数据，总记录数：${total}`);
      res.json(
        util.FormatJSONData(200, `卖家${seller}的出售商品列表`, {
          total: total,
          data: goods,
          currentPage: Math.ceil(offset / limit) + 1,
          totalPages: Math.ceil(total / limit),
        })
      );
    } catch (err) {
      util.err("查询商品失败", err);
      util.FormatJSONData(res, 500, "服务器内部错误");
    }
  })();
}

//通过商品名查询商品，测试通过
function getGoodsByPrice(req, res) {
  (async () => {
    try {
      const min_price = parseFloat(req.query.min_price);
      const max_price = parseFloat(req.query.max_price);
      const limit =
        parseInt(req.query.limit) < 0 ? -1 : parseInt(req.query.limit);
      const offset =
        parseInt(req.query.offset) < 0 ? -1 : parseInt(req.query.offset);
      const db = GoodsDB.getInstance();
      await db.connect();
      const goods = await db.findByPrice(min_price, max_price, limit, offset);
      if (!goods.length) {
        res.json(util.FormatJSONData(403, "查询结果为空", goods));
      } else {
        res.json(
          util.FormatJSONData(
            200,
            `查询价格在${min_price}到${max_price}的商品列表`,
            goods
          )
        );
        util.log(`查询价格在${min_price}到${max_price}的商品列表`);
      }
    } catch (err) {
      util.FormatJSONData(res, 500, "服务器内部错误");
    }
  })();
}

function browseGoods(req, res) {
  const goods_id = parseInt(req.params.goods_id);
  (async () => {
    try {
      const db = GoodsDB.getInstance();
      await db.connect();
      const result = await db.findById(parseInt(goods_id));
      if (!result) {
        res.json(util.FormatJSONData(404, `商品不存在`));
      }
      await db.addBrowseCount(parseInt(goods_id));
      res.json(util.FormatJSONData(200, `浏览商品${goods_id}成功`));
    } catch (err) {
      util.FormatJSONData(res, 500, "服务器内部错误");
    }
  })();
}

function setGoodsStatus(req, res) {
  (async () => {
    try {
      const goods_id = parseInt(req.query.goods_id);
      const status = parseInt(req.query.status);
      const db = GoodsDB.getInstance();
      await db.connect();
      const result = await db.findById(parseInt(goods_id));
      if (!result) {
        res.json(util.FormatJSONData(404, `商品不存在`));
      }
      util.log(`设置商品${goods_id}状态为${status}`);
      await db.setStatus(goods_id, status);
      res.json(
        util.FormatJSONData(200, `设置商品${goods_id}状态为${status}成功`)
      );
    } catch (err) {
      util.FormatJSONData(res, 500, "服务器内部错误");
    }
  })();
}

function removeGoods(req, res) {
  (async () => {
    try {
      const goods_id = parseInt(req.params.goods_id);
      const db = GoodsDB.getInstance();
      await db.connect();
      const result = await db.findById(parseInt(goods_id));
      if (!result) {
        res.json(util.FormatJSONData(404, `商品不存在`));
      }
      util.log(`删除商品${goods_id}`);
      await db.remove(goods_id);
      res.json(util.FormatJSONData(200, `删除商品${goods_id}成功`));
    } catch (err) {
      util.FormatJSONData(res, 500, "服务器内部错误");
    }
  })();
}

//测试通过
function updateGoods(req, res) {
  (async () => {
    try {
      const db = GoodsDB.getInstance();
      await db.connect();
      const info = await db.findById(parseInt(req.body.goods_id));
      if (!info) {
        res.json(util.FormatJSONData(404, `商品不存在`));
      }
      const goods = {
        goods_id: parseInt(req.body.goods_id),
        goods_name: req.body.goods_name || info.goods_name,
        goods_desc: req.body.goods_desc || info.goods_desc,
        goods_price: parseFloat(req.body.goods_price) || info.goods_price,
        goods_stock: parseInt(req.body.goods_stock) || info.goods_stock,
        goods_img: req.body.goods_img || info.goods_img,
        goods_detail: parseInt(req.body.goods_detail) || info.goods_detail,
        goods_category:
          parseInt(req.body.goods_category) || info.goods_category,
      };

      const result = await db.update(goods, req.body);

      if (!result) {
        res.json(util.FormatJSONData(404, "商品不存在", result));
      } else {
        res.json(util.FormatJSONData(200, "更新商品成功", result));
      }
    } catch (err) {
      util.FormatJSONData(res, 500, "服务器内部错误");
    }
  })();
}

module.exports = {
  addGoods,
  addImg,
  getGoodsById,
  getGoodsByName,
  getGoodsByCategory,
  getGoodsBySeller,
  getGoodsByPrice,
  setGoodsStatus,
  removeGoods,
  updateGoods,
  browseGoods,
  getAll,
};
